const fs = require("fs");
const path = require("path");

// 确保日志目录存在
const logDir = path.join(__dirname, "../logs");
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

const colors = {
  reset: "\x1b[0m",
  brightBlue: "\x1b[94m",
  cyan: "\x1b[36m",
  green: "\x1b[32m",
  yellow: "\x1b[33m",
  red: "\x1b[31m",
  gray: "\x1b[90m",
};

const loggerMiddleware = (req, res, next) => {
  // 跳过非api请求
  if (!req.path.startsWith("/api")) {
    return next();
  }
  const startTime = Date.now();
  const clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
  const beijingTime = new Date().toLocaleString("zh-CN", {
    timeZone: "Asia/Shanghai",
  });
  res.on("finish", () => {
    const logData = {
      ip: clientIp,
      time: beijingTime,
      method: req.method,
      path: req.originalUrl,
      status: res.statusCode,
      duration: `${Date.now() - startTime}ms`,
      query: req.query,
      body: req.body,
    };

    if (
      req.originalUrl == "/api/auth/login" ||
      req.originalUrl == "/api/auth/register"
    ) {
      return;
    }

    // 修改时间格式为北京时间（新增以下3行）
    const beijingTimestamp =
      new Date()
        .toLocaleString("zh-CN", {
          timeZone: "Asia/Shanghai",
          hour12: false,
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          fractionalSecondsDigits: 3,
        })
        .replace(/(\d+)\/(\d+)\/(\d+),/, "$3-$1-$2T") + "+08:00";

    const logString = `[${beijingTimestamp}] ${JSON.stringify(logData)}\n`;
    const logFile = path.join(
      logDir,
      `${new Date().toISOString().split("T")[0]}.log`
    );

    fs.appendFile(logFile, logString, (err) => {
      if (err) console.error("写入日志文件失败:", err);
    });

    // 控制台彩色输出（新增部分）
    const statusColor =
      res.statusCode >= 500
        ? colors.red
        : res.statusCode >= 400
        ? colors.yellow
        : res.statusCode >= 200
        ? colors.green
        : colors.cyan;

    const coloredLog = [
      `${colors.brightBlue}[${beijingTime}]${colors.reset}`,
      `${colors.green}${req.method}${colors.reset}`,
      `${colors.cyan}${req.originalUrl}${colors.reset}`,
      `${statusColor}${res.statusCode}${colors.reset}`,
      `${colors.yellow}${Date.now() - startTime}ms${colors.reset}`,
      `${colors.brightBlue}${clientIp}${colors.reset}`,
      `${colors.gray}query=${JSON.stringify(req.query)}${colors.reset}`,
      `${colors.gray}body=${JSON.stringify(req.body)}${colors.reset}`,
    ].join(" ");

    console.log(coloredLog);
  });

  next();
};

module.exports = loggerMiddleware;
